package com.cnblogs.leizia.crm.workbench.service.impl;

import com.cnblogs.leizia.crm.utils.DateTimeUtil;
import com.cnblogs.leizia.crm.utils.SqlSessionUtil;
import com.cnblogs.leizia.crm.workbench.dao.TranDao;
import com.cnblogs.leizia.crm.workbench.domain.Tran;
import com.cnblogs.leizia.crm.workbench.domain.TranHistory;
import com.cnblogs.leizia.crm.workbench.service.TranService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author leizi
 * @create 2021-04-05 0:03
 */
public class TranServiceImpl implements TranService {
    /**
     * 保存交易
     *
     * @param tran
     */
    @Override
    public void saveTran(Tran tran) {
        TranDao tranDao = SqlSessionUtil.getSqlSession().getMapper(TranDao.class);

        tranDao.saveTran(tran);
    }

    /**
     * 交易详情
     *
     * @param tranId
     * @return
     */
    @Override
    public Tran detail(String tranId) {
        TranDao tranDao = SqlSessionUtil.getSqlSession().getMapper(TranDao.class);

        Tran tran = tranDao.detail(tranId);

        return tran;
    }

    /**
     * 根据交易id获取交易历史
     *
     * @param tranId
     * @return
     */
    @Override
    public List<TranHistory> tranHistoryList(String tranId) {
        TranDao tranDao = SqlSessionUtil.getSqlSession().getMapper(TranDao.class);

        List<TranHistory> tranHistories = tranDao.tranHistoryList(tranId);

        return tranHistories;
    }

    /**
     * 修改交易内容
     *
     * @param tran
     * @return
     */
    @Override
    public Tran tranChangeStage(Tran tran, String possibility) {
        TranDao tranDao = SqlSessionUtil.getSqlSession().getMapper(TranDao.class);
        // 修改交易内容
        tranDao.tranChangeStage(tran);

        // 添加交易历史记录
        TranHistory tranHistory = new TranHistory();
        tranHistory.setTranId(tran.getId());
        tranHistory.setStage(tran.getStage());
        tranHistory.setMoney(tran.getMoney());
        tranHistory.setCreateTime(DateTimeUtil.getSysTime());
        tranHistory.setCreateBy(tran.getCreateBy());
        tranHistory.setExpectedDate(tran.getExpectedDate());
        tranHistory.setPossibility(possibility);
        tranDao.saveTranHistory(tranHistory);

        // 获取更新后交易内容
        return tranDao.getTranById(tran.getId());

    }

    /**
     * 获取交易统计图表
     *
     * @return
     */
    @Override
    public Map<String, Object> getChartList() {
        TranDao tranDao = SqlSessionUtil.getSqlSession().getMapper(TranDao.class);
        // 获取各交易阶段数量
        List<Map<String, Integer>> chartList = tranDao.getChartList();
        // 获取总数
        int total = tranDao.getTotal();

        HashMap<String, Object> map = new HashMap<>();
        map.put("dataList", chartList);
        map.put("total", total);

        return map;
    }
}
